import Item from "../Item/Item";
import Player from "./Player";
import BagView from "../View/BagView";
import ItemView from "../View/ItemView";

export default class BagManager {

    m_bagView: BagView = null;
    m_owner: Player = null;
    m_items: Array<Item> = [];//物品列表

    public constructor(){
        Object.defineProperty(this, "m_owner", { enumerable: false })
    }

    public init(owner: Player):void{
        this.m_owner = owner;
    }

    //增加物品
    public addItem(item: Item): void {
        //设置所有者
        item.m_owner = this.m_owner;

        let isExist: boolean = false;
        if (item.m_isStacking) {
            for (let it of this.m_items) {
                if (it.m_id == item.m_id) {
                    //可叠加并存在直接加数量
                    it.m_count += item.m_count;
                    it.noticViewChange();
                    isExist = true;
                    break;
                }
            }
        }
        if (!isExist) {
            //不存在直接插入
            this.m_items.push(item);

            this.noticBagViewAddItem(item);
        }
    }

    //减少库存
    public reduceInventory(item: Item, count: number): void {
        let idx = this.m_items.indexOf(item);
        if (idx < 0) {
            console.error("Item not exist.idx=%d", idx);
            return;
        }
        if (item.m_count < count) {
            console.error("Item count not enough.");
            item.m_count = 1;
        }
        else {
            item.m_count -= count;
        }

        if (item.m_count <= 0) {
            //移除
            this.m_items.splice(idx, 1);
            item.m_count = 1;
            item.noticViewChange(true);
            //console.log(this.m_items);
        }
        else{
            item.noticViewChange();
        }
    }

    public getItemByIndex(idx: number):Item {
        if(idx >= this.m_items.length){
            return null;
        }
        
        return this.m_items[idx];
    }

    public noticBagViewAddItem(item: Item):void{
        if(this.m_bagView){
            this.m_bagView.addItemView(item);
        }
    }
}
